﻿using System;
using System.IO.Ports;
using System.Threading;
using System.Collections.Generic;

namespace Microsoft.Samples.Kinect.BodyBasics.Controls
{
    public class Comm
    {
        //声明事件类型
        public delegate void ReadBufferHandle(byte[] readBuffer);
        public event ReadBufferHandle DataReceived;

        //被封装的串口类型
        //public SerialPort serialPort;
        public System.IO.Ports.SerialPort serialPort;

        //发送线程
        private Thread sendThread;
        private Queue<Package> sendQueue;
        //接收线程
        private Thread receiveThread;
        //读取标志位
        volatile bool keepReading = false;
        volatile bool keepSending = false;

        //构造方法
        public Comm(string portName)
        {
            serialPort = new System.IO.Ports.SerialPort();
            serialPort.PortName = portName;
            serialPort.BaudRate = 9600;
            serialPort.StopBits = StopBits.One;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;

            sendQueue = new Queue<Package>();
            sendThread = null;
            receiveThread = null;
            keepReading = false;

        }

        public Comm()
        {
            serialPort = new System.IO.Ports.SerialPort();

            sendQueue = new Queue<Package>();
            sendThread = null;
            receiveThread = null;
            keepReading = false;
        }

        //判断串口是否打开
        public bool IsOpen
        {
            get { return serialPort.IsOpen; }
        }

        public string Name
        {
            get { return serialPort.PortName; }
            set
            {
                serialPort.PortName = value;
                
            }
        }

        //开始读取
        private void startReading()
        {
            if (!keepReading)
            {
                keepReading = true;
                receiveThread = new Thread(readPort);
                receiveThread.Start();
            }
        }

        //开始发送
        private void startSending()
        {
            if (!keepSending)
            {
                keepSending = true;
                sendThread = new Thread(sendPort);
                sendThread.Start();
                Console.WriteLine("sendthread started.");
            }
        }

        //添加包
        public void AddPackge(Package package)
        {
            sendQueue.Enqueue(package);
        }

        //发送数据线程
        private void sendPort()
        {
            while (keepSending)
            {
                if (IsOpen)
                {
                    if (sendQueue.Count > 0)
                    {
                        Package package = sendQueue.Dequeue();
                        byte[] bytesSend = package.SendBuffer;
                        WritePort(bytesSend, 0, bytesSend.Length);
                        Console.WriteLine("data sended.");
                        sendQueue.Clear();

                    }
                }
            }
        }

        //串口读取
        private void readPort()
        {
            while (keepReading)
            {
                if (IsOpen)
                {
                    int count = serialPort.BytesToRead;
                    if (count > 0)
                    {
                        byte[] readBuffer = new byte[count];
                        try
                        {
                            //是否需要从外部启动事件
                            serialPort.Read(readBuffer, 0, count);
                            DataReceived?.Invoke(readBuffer);
                            Thread.Sleep(100);
                        }
                        catch (TimeoutException)
                        {

                        }
                    }
                }
            }
        }

        //关闭读取线程
        private void stopReading()
        {
            if (keepReading)
            {
                keepReading = false;
                receiveThread.Join();
                receiveThread = null;
            }
        }

        //打开串口
        public void Open()
        {
            Close();
            serialPort.Open();
            if (serialPort.IsOpen)
            {
                startReading();
                startSending();
                Console.WriteLine("serialPort open successfully...");
            }
            //else
            //{
            //    Console.WriteLine("open fail.");
            //    MessageBox.Show("open fail");
            //}
        }

        //关闭串口
        public void Close()
        {
            stopReading();
            serialPort.Close();
        }

        //写数据
        public void WritePort(byte[] send, int offSet, int count)
        {
            if (IsOpen)
            {
                serialPort.Write(send, offSet, count);
            }
        }
    }
}
